package org.example.crm.interceptor;

import org.example.crm.dao.UserMapper;
import org.example.crm.exceptions.NoLoginException;
import org.example.crm.utils.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 非法访问拦截
 * 继承HandlerInterceptorAdapter适配器
 */

public class NoLoginInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private UserMapper userMapper;

    /**
     * 拦截用户是否是登录状态
     * 在目标方法（资源）执行前执行的方法
     * 返回boolean
     * 如果为true，表示目标方法可用被执行
     * 如果为false，表示阻止目标方法执行
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取cookie中的用户Id
        Integer userId = LoginUserUtil.releaseUserIdFromCookie(request);
        //判断用户Id是否为空，且数据库中是否存在改userId的记录
        if (userId == null || userMapper.selectByPrimaryKey(userId) == null) {
            //抛出未登录异常
            throw new NoLoginException();
        }
        return true;
    }
}
